<template lang='pug'>
  #search
    .search-wrap
      input.form-control(
        type="text"
        class="search"
        :placeholder="placeholders"
        v-model="searchVal"
        @keyup="startSearch"
        @keyup.enter.self="getSearchData")
      .search-tool
        span
          i(:class="['iconfont', 'icon-' + icon]")
        span(@click="closeSearch" v-if="isShow")
          i.iconfont.icon-close
    .list-wrap(v-show="isShow" v-loading="isLoading")
      ul
        li(
          v-for="(item,index) in NewItems"
          v-bind:key="index"
          v-show="searchVal !== '' && isShow"
          v-on:click="searchChange(item)"
          :class="{'active': item.act}")
          .msg-item1
            .msg-item1-left
              i(:class="['iconfont', 'icon-positioning']")
              | {{'【编号：' + item.siteCode + '】'}}
            .msg-item1-right(v-text="`${deviceType[item.deviceName].label}`")
          .msg-item2 名称：{{(item.siteName === null ? '-' : item.siteName)}}
          .msg-item2 地址：{{(item.installAddress === null ? '-' : item.address)}}
        li.search-tooltip(v-show="NewItems.length === 0 && searchVal !== ''") {{isLoading?'搜索中':noResult}}
</template>

<script>
import { debounce } from 'lodash'
import { httpGet } from '@/utils/api'
import { deviceTypeList, deviceType } from '../../../config/marker'
/**
 * @name 带异步请求的搜索框
 * @author 蔡鑫权
 * @desc
 * 输入内容自动搜索（用防抖）
 * 搜索监听键盘enter
 * 搜索出来的options列表支持自定义展示
 * options默认以列表展示，默认限制显示5条数据，可跳转查看全部
 * 搜索出来的内容允许广播给父组件
 */
export default {
  name: 'SearchBar',
  props: {
    ajax: {
      type: Object,
      default: () => ({
        url: '',
        params: {}
      })
    }, // 发起请求的对象
    placeholders: {
      type: String,
      default: '请输入搜索内容'
    },
    icon: {
      type: String,
      default: 'search'
    },
    noResult: {
      type: String,
      default: '没有搜索到数据'
    }, // 没有数据提示
    limit: {
      type: Number,
      default: 0
    }, // 默认显示搜索出来的条数
    showSearchBarList: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      isshowAll: false,
      isShow: false,
      searchVal: '',
      NewItems: [],
      results: [],
      isLoading: false,
      // 设备类型列表
      deviceTypeList,
      // 设备类型列表（Object）
      deviceType
    }
  },
  computed: {
    computLimit () {
      return this.isshowAll ? this.NewItems.length : this.limit
    }
  },
  watch: {
    showSearchBarList () {
      this.isShow = false
      this.searchVal = ''
    }
  },
  methods: {
    // 执行搜索
    startSearch () {
      if (this.searchVal !== '') {
        this.isShow = true
        this.isLoading = true
        this.getSearchData()
      } else {
        this.isShow = false
        this.isLoading = false
      }
    },
    // 获取搜索得到的数据
    getSearchData: debounce(function (e) {
      httpGet({
        url: `pn/dpa/monitor/mapSearch?keyword=${this.searchVal}&deviceNames=LUF,DMA,DPAF,PT`
      }).then(({data}) => {
        this.isLoading = false
        // this.isShow = true
        if (data) {
          this.NewItems = data
          if (e) this.isshowAll = e.keyCode === 13
        } else {
          this.NewItems = []
        }
      })
    }, 500),
    /* 搜索出来的数据广播出去 */
    searchChange (value) {
      this.NewItems.map(item => {
        this.$set(item, 'act', Number(item.id) === Number(value.id))
      })
      this.searchVal = value.installAddress
      const position = [value.longitude, value.latitude]
      this.$emit('positioning', position, value)
      this.isShow = false
    },
    closeSearch () {
      this.searchVal = ''
      this.isShow = false
    }
  }
}
</script>

<style lang="sass" scoped>
#search
  background-color: #fff
  border: 1px solid #ccc
  border-radius: 4px
  box-shadow: 0px 0px 10px #dfdfdf
  width: 300px
  z-index: 2
  .search-wrap
    width: 100%
    position: relative
    input
      padding: 6px 12px
    .search-tool
      position: absolute
      top: 9px
      right: 6px
      z-index: 3
      // cursor: pointer
      span
        padding-right: 10px
        cursor: pointer
  .list-wrap
    width: 100%
    background-color: #fff
    border: 1px solid rgba(0, 0, 0, 0.07)
    position: absolute
    top: 32px
    border-bottom-left-radius: 4px
    border-bottom-right-radius: 4px
    font-size: 12px
    min-height: 54px
    ul
      max-height: 500px
      overflow: hidden
      overflow-y: scroll
    li
      border-bottom: 1px solid #ebeef5
      padding: 6px
      .msg-item1
        height: 18px
        color: #555
        line-height: 18px
        overflow: hidden
        white-space: nowrap
        text-overflow: ellipsis
        display: flex
        justify-content: space-between
        .msg-item1-right
          overflow: hidden
          white-space: nowrap
          text-overflow: ellipsis
      .msg-item2
        width: 100%
        color: #555
        text-align: left
        display: -webkit-box
        -webkit-line-clamp: 2
        -webkit-box-orient: vertical
        overflow: hidden
        text-overflow: ellipsis
    li:hover
      cursor: pointer
      background: #f5f7fa
    .active
      background: #dfdfdf
    .list-icon-right
      text-align: right
      line-height: 1
      padding-right: 10px
      cursor: pointer
    .search-tooltip
      line-height: 100px
      text-align: center
</style>
